import { userStore } from "@/store/user"
import { loading } from "@/utils/loading"
import { ElMessage } from "element-plus"
import Cookies from "js-cookie"
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"

const staticRoutes: Array<RouteRecordRaw> = [

    {
        path: "/login",
        name: "Login",
        component: () => import("@/view/login/index.vue")
    },
    {
        path: "/*",
        name: "notFound",
        component: () => import("@/view/404/index.vue")
    }
]
const router = createRouter({
    history: createWebHistory(),
    routes: staticRoutes
})

router.beforeEach((to, from, next) => {
    if (Cookies.get("token")) {
        if (to.path === "/login") { next() }
        if (userStore().$state.routes.length === 0) {
            loading.start()
            userStore().getUserInfo().then((addRoute: any) => {
                console.log(addRoute);
                router.addRoute(userStore().$state.routes[0])
                console.log(router.getRoutes());
                next({ ...to, replace: true })
            })
        } else {
            next()
        }
    } else {
        if (to.path == "/login") { next() }
        else {
            next({ ...to })
        }
    }
})

export default router